﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Prism.Regions;
using RecipeDemo.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RecipeDemo.ViewModels
{
    public partial class MPEditorViewModel : ObservableObject, INavigationAware
    {
        private readonly ScanPointRepository _scanPointRepo;

        [ObservableProperty]
        private ScanPointViewModel reference;
        IRegionManager _regionManager;
        public MPEditorViewModel(ScanPointRepository scanPointRepo, IRegionManager regionManager)
        {
            _regionManager = regionManager;
            _scanPointRepo = scanPointRepo;
        }
        Guid _currentId;

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters.TryGetValue<Guid>("ScanPointId", out var id))
            {
                _currentId = id;
                var item = _scanPointRepo.GetById(id);
                Reference = item?.ScanPoint;
            }
        }

        public bool IsNavigationTarget(NavigationContext navigationContext) => true;
        public void OnNavigatedFrom(NavigationContext navigationContext) { }

        [RelayCommand]
        private void Save()
        {
            if (Reference == null) return;

            // 获取当前编辑的 ScanPointItem
            var currentItem = _scanPointRepo.GetById(_currentId);
            currentItem.ScanPoint = Reference;

            // 更新仓库
            _scanPointRepo.AddOrUpdate(currentItem);
            _regionManager.RequestNavigate("MainRegion", "RecipeView");
        }


        //    [RelayCommand]
        //    private void OpenEditor()
        //    {
        //        if (SelectedScanPointItem == null) return;

        //        var parameters = new NavigationParameters
        //{
        //    { "ScanPointId", SelectedScanPointItem.Id }
        //};
        //        _regionManager.RequestNavigate("MainRegion", "MPEditorView", parameters);
        //    }
    }
}
